package com.intelap.rp3.coherence.pruebaConcepto;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;

import com.intelap.rp3.coherence.pruebaConcepto.Cliente.Item;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.border.BevelBorder;

@SuppressWarnings("serial")
class ClienteUI extends JFrame {

	private JPanel contentPane;
	private JTable itemsTable;
	private JTextField contadorTextField;
	private JButton verContadorButton;
	private JButton incrementarContadorButton;
	private JPanel panelSur;
	private JButton agregarItemButton;
	private JScrollPane scrollPane;

	/**
	 * Launch the application.
	 */
	static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ClienteUI frame = new ClienteUI();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	private ClienteUI() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);

		JPanel panelNorte = new JPanel();
		contentPane.add(panelNorte, BorderLayout.NORTH);

		verContadorButton = new JButton("ver contador");
		panelNorte.add(verContadorButton);

		contadorTextField = new JTextField();
		panelNorte.add(contadorTextField);
		contadorTextField.setColumns(10);

		incrementarContadorButton = new JButton("incrementar contador");
		panelNorte.add(incrementarContadorButton);

		JPanel panelCentral = new JPanel();
		contentPane.add(panelCentral, BorderLayout.CENTER);

		scrollPane = new JScrollPane();
		panelCentral.add(scrollPane);

		itemsTable = new JTable();
		scrollPane.setViewportView(itemsTable);

		panelSur = new JPanel();
		panelSur.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null,
				null, null));
		contentPane.add(panelSur, BorderLayout.SOUTH);

		agregarItemButton = new JButton("agregar \u00EDtem");
		panelSur.add(agregarItemButton);
	}

	private void setModelo(ClienteUIModel modelo) {
		this.contadorTextField.setDocument(modelo.contadorDocument);
		this.verContadorButton.setAction(modelo.verContadorAction);
		this.incrementarContadorButton
				.setAction(modelo.incrementarContadorAction);
		this.itemsTable.setModel(modelo.itemsDataModel);
		this.agregarItemButton.setAction(modelo.agregarItemAction);
	}

	private static class ClienteUIModel {
		public final Action agregarItemAction;
		public final TableModel itemsDataModel;
		public final Action incrementarContadorAction;
		public final Action verContadorAction;
		public final Document contadorDocument;

		public ClienteUIModel(Action agregarItemAction,
				TableModel itemsDataModel, Action incrementarContadorAction,
				Action verContadorAction, Document contadorDocument) {
			this.agregarItemAction = agregarItemAction;
			this.itemsDataModel = itemsDataModel;
			this.incrementarContadorAction = incrementarContadorAction;
			this.verContadorAction = verContadorAction;
			this.contadorDocument = contadorDocument;
		}
	}

	static void showCliente(final Cliente cliente, final String idPuesto) {
		final Logger logger = Logger.getLogger("Puesto-" + idPuesto);

		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {

					final PlainDocument contadorDocument = new PlainDocument();

					final AbstractTableModel itemsDataModel = new AbstractTableModel() {
						@Override
						public int getRowCount() {
							return cliente.getItemsSucursal().size();
						}

						@Override
						public int getColumnCount() {
							return 5;
						}

						@Override
						public Object getValueAt(int rowIndex, int columnIndex) {
							List<Item> lista = new ArrayList<Item>(cliente
									.getItemsSucursal());
							Collections.sort(lista, new Comparator<Item>() {
								@Override
								public int compare(Item o1, Item o2) {
									try {
										return (int) (o1.getNroOperacion() - o2
												.getNroOperacion());
									} catch (Exception e) {
										logger.info(e.getMessage());
										return 0;
									}
								}
							});
							Item item = lista.get(rowIndex);

							switch (columnIndex) {
							case 0:
								return item.getNroOperacion();
							case 1:
								return item.getIdPuesto();
							case 2:
								return item.getImporte();
							case 3:
								return new SimpleDateFormat("HH:mm:ss")
										.format(item.getDate());
							case 4:
								return cliente.getItemsPropios().contains(item) ? "propio"
										: "ajeno";
							default:
								throw new IndexOutOfBoundsException();
							}
						}

						@Override
						public String getColumnName(int column) {
							switch (column) {
							case 0:
								return "nro Op Sucu";
							case 1:
								return "puesto";
							case 2:
								return "importe";
							case 3:
								return "fecha";
							case 4:
								return "origen";
							default:
								return null;
							}
						}
					};

					final Action agregarItemAction = new AbstractAction(
							"agregar nuevo item") {
						@Override
						public void actionPerformed(ActionEvent e) {
							cliente.agregarNuevoItem();
							itemsDataModel.fireTableDataChanged();
						}

					};

					final Action verContadorAction = new AbstractAction(
							"ver contador") {
						@Override
						public void actionPerformed(ActionEvent e) {
							try {
								contadorDocument.replace(0,
										contadorDocument.getLength(), ""
												+ cliente.getContador()
														.getValor(), null);
							} catch (BadLocationException e1) {
							}
						}
					};
					verContadorAction.actionPerformed(null);

					final Action incrementarContadorAction = new AbstractAction(
							"incrementar contador") {
						@Override
						public void actionPerformed(ActionEvent e) {
							cliente.getContador().incrementar();
							verContadorAction.actionPerformed(e);
						}
					};

					final ClienteUIModel clienteUiModel = new ClienteUIModel(
							agregarItemAction, itemsDataModel,
							incrementarContadorAction, verContadorAction,
							contadorDocument);

					ClienteUI clienteUI = new ClienteUI();
					clienteUI.setTitle("Puesto: " + idPuesto);
					clienteUI.setModelo(clienteUiModel);
					clienteUI.pack();
					clienteUI.setVisible(true);
				} catch (Exception e) {
					logger.log(Level.SEVERE, "", e);
				}
			}
		});
	}
}
